//
//  SysSettingViewController.m
//  Brand
//
//  Created by Woody Yan on 11/05/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "config.h"
#import "CCSwitch.h"
#import "SysSettingViewController.h"
#import "AppDelegate.h"
#import "PersonalInfoViewController.h"
#import "SystemSettingInfoVC.h"
#import "LoginViewController.h"
#import "Header.h"
#import <Frontia/Frontia.h>


#define Padding 20
#define buttonHeight 44
#define bigBtnHeight 56



@interface SysSettingViewController ()

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UIButton *personSetting;
@property (strong, nonatomic) UIButton *networkSetting;
@property (strong, nonatomic) UIButton *pushSetting;
@property (strong, nonatomic) UIButton *clearSpace;
@property (strong, nonatomic) UILabel  *clearLabel;
@property (strong, nonatomic) UIButton *privateTerm;
@property (strong, nonatomic) UIButton *feedBack;
@property (strong, nonatomic) UIButton *copyright;
@property (strong, nonatomic) UIButton *evaluation;
@property (strong, nonatomic) UIButton *update;
@property (strong, nonatomic) UIButton *logout;

@property (strong, nonatomic) CCSwitch* sw;
@property (strong, nonatomic) CCSwitch* pushSw;

@end

@implementation SysSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    
    UIImage *background = [UIImage imageNamed:@"Layer.png"];
	self.view.backgroundColor = [UIColor colorWithPatternImage:background];
	
	UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	backBtn.frame = CGRectMake(0, 0, 44, 44);
    UIImage *back = [UIImage imageNamed:@"return.png"];
    [backBtn setImage:back forState:UIControlStateNormal];
	[backBtn addTarget:self action:@selector(popOut) forControlEvents:UIControlEventTouchUpInside];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
	
	UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
	title.text = @"系统设置";
    title.font = [UIFont systemFontOfSize:16];
    title.backgroundColor = [UIColor clearColor];
	title.textColor = ColorWithHex(0XFFFFFF);
	title.textAlignment = NSTextAlignmentCenter;
	
	UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
	navBar.backgroundColor = [UIColor clearColor];
	
	[navBar addSubview:backBtn];
	[navBar addSubview:title];
    [self drawNavTopContentView:navBar];
    
    [self initUI];
    
}

- (void) initUI
{
    CGFloat yDelta;
    
    if (isiOS7) { yDelta = 0.0f; } else { yDelta = 20.0f;}
    
    //ScrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64 - yDelta, 320, kScreen_Height - 64)];
    
    CGFloat offset;
    if (isiPhone5) {
        offset = 1;
    } else {
        offset = 88;
    }

    self.scrollView.contentSize = CGSizeMake(kScreen_Width, kScreen_Height - 64 + offset);
    self.scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    //Person Setting
    self.personSetting = [UIButton buttonWithType:UIButtonTypeCustom];
    self.personSetting.frame = CGRectMake(10, 0, kScreen_Width  - 20, bigBtnHeight);
    [self.personSetting setTitle:@"个人设置" forState:UIControlStateNormal];
    self.personSetting.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.personSetting addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.personSetting.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.personSetting.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 10, 0);
    [self.scrollView addSubview:self.personSetting];
    
    UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(10, self.personSetting.bottom-18, kScreen_Width - 20, 10)];
    label.text = @"设置昵称,头像,阵营";
    label.font  = [UIFont systemFontOfSize:9];
    label.textColor = RGB(167, 167, 171);
    label.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:label];
    
    //split line
    UIImage *line = [UIImage imageNamed:@"1px_line.png"];
    UIImageView *splitLine0 = [[UIImageView alloc] initWithImage:line];
    splitLine0.frame = CGRectMake(10, self.personSetting.frame.origin.y + bigBtnHeight + 1, 300, 1);
    [self.scrollView addSubview:splitLine0];
    
    
    //Network Setting
    self.networkSetting = [UIButton buttonWithType:UIButtonTypeCustom];
    self.networkSetting.frame = CGRectMake(10, splitLine0.frame.origin.y + 1, kScreen_Width  - 20, bigBtnHeight);
    [self.networkSetting setTitle:@"网络设置" forState:UIControlStateNormal];
    self.networkSetting.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.networkSetting addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.networkSetting.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
     self.networkSetting.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 10, 0);
    [self.scrollView addSubview:self.networkSetting];
    
    UILabel* label2 = [[UILabel alloc]initWithFrame:CGRectMake(10, self.networkSetting.bottom - 18, kScreen_Width - 20, 10)];
    label2.text = @"是否允许2G/3G模式下载";
    label2.font  = [UIFont systemFontOfSize:9];
    label2.textColor = RGB(167, 167, 171);
    label2.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:label2];

    
    
    //CCSwich
    self.sw = [[CCSwitch alloc] initWithFrame:CGRectMake(240, 14, 50, 30)];
    self.sw.backgroundColor = [UIColor clearColor];
    self.sw.tintColor =ColorWithHex(0X808080);
    self.sw.onTintColor = ColorWithHex(0X00E259);
    self.sw.onText =@"On";
    self.sw.offText = @"Off";
    self.sw.on = [kUser boolForKey:IsAllowedDownloadIn3G];
    [self.sw addTarget:self action:@selector(handleSwithEvent:) forControlEvents:UIControlEventValueChanged];
    [self.networkSetting addSubview:self.sw];
    
    
    //split line
    UIImageView *splitLine1 = [[UIImageView alloc] initWithImage:line];
    splitLine1.frame = CGRectMake(10, self.networkSetting.frame.origin.y + bigBtnHeight + 1, 300, 1);
    [self.scrollView addSubview:splitLine1];
    
    //Push Setting
    self.pushSetting = [UIButton buttonWithType:UIButtonTypeCustom];
    self.pushSetting.frame = CGRectMake(10, splitLine1.frame.origin.y + 1, kScreen_Width  - 20, bigBtnHeight);
    [self.pushSetting setTitle:@"推送设置" forState:UIControlStateNormal];
    self.pushSetting.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.pushSetting addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.pushSetting.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
     self.pushSetting.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 10, 0);
    [self.scrollView addSubview:self.pushSetting];
    
    UILabel* label3 = [[UILabel alloc]initWithFrame:CGRectMake(10, self.pushSetting.bottom - 18, kScreen_Width - 20, 10)];
    label3.text = @"是否接受PUSH消息";
    label3.font  = [UIFont systemFontOfSize:9];
    label3.textColor = RGB(167, 167, 171);
    label3.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:label3];

    
    //CCSwich
    self.pushSw = [[CCSwitch alloc] initWithFrame:CGRectMake(240, 14, 50, 30)];
    self.pushSw.backgroundColor = [UIColor clearColor];
    self.pushSw.tintColor =ColorWithHex(0X808080);
    self.pushSw.onTintColor = ColorWithHex(0X00E259);
    self.pushSw.onText =@"On";
    self.pushSw.offText = @"Off";
    self.pushSw.on = [kUser boolForKey:IsAllowedPush];
    NSLog(@"on2 = %d",[kUser boolForKey:IsAllowedPush]);
    [self.pushSw addTarget:self action:@selector(handleSwithEvent:) forControlEvents:UIControlEventValueChanged];
    [self.pushSetting addSubview:self.pushSw];
    
    //split line
    UIImageView *splitLine2 = [[UIImageView alloc] initWithImage:line];
    splitLine2.frame = CGRectMake(10, self.pushSetting.frame.origin.y + bigBtnHeight + 1, 300, 1);
    [self.scrollView addSubview:splitLine2];
    
    
    //clear label
    self.clearLabel = [[UILabel alloc]initWithFrame:CGRectMake(260, splitLine2.frame.origin.y +10, 44, 24)];
    self.clearLabel.text = @"0.0M";
    self.clearLabel.font = [UIFont systemFontOfSize:14];
    self.clearLabel.backgroundColor = [UIColor clearColor];
    self.clearLabel.textColor = RGB(245, 245, 245);
    [self.scrollView addSubview:self.clearLabel];
    
    //Clear Space
    self.clearSpace = [UIButton buttonWithType:UIButtonTypeCustom];
    self.clearSpace.frame = CGRectMake(10, splitLine2.frame.origin.y + 1, kScreen_Width  - 20, buttonHeight);
    [self.clearSpace setTitle:@"清除缓存" forState:UIControlStateNormal];
    self.clearSpace.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.clearSpace addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.clearSpace.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.scrollView addSubview:self.clearSpace];
    
    
    
    //split line
    UIImageView *splitLine3 = [[UIImageView alloc] initWithImage:line];
    splitLine3.frame = CGRectMake(10, self.clearSpace.frame.origin.y + buttonHeight + 1, 300, 1);
    [self.scrollView addSubview:splitLine3];
    
    
    
    // Private Term
    self.privateTerm = [UIButton buttonWithType:UIButtonTypeCustom];
    self.privateTerm.frame = CGRectMake(10, splitLine3.frame.origin.y + 1, kScreen_Width  - 20, buttonHeight);
    [self.privateTerm setTitle:@"隐私政策" forState:UIControlStateNormal];
    self.privateTerm.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.privateTerm addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.privateTerm.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.scrollView addSubview:self.privateTerm];
    
    
    //split line
    UIImageView *splitLine4 = [[UIImageView alloc] initWithImage:line];
    splitLine4.frame = CGRectMake(10, self.privateTerm.frame.origin.y + buttonHeight + 1, 300, 1);
    [self.scrollView addSubview:splitLine4];
    
    
    // FeedBack
    self.feedBack = [UIButton buttonWithType:UIButtonTypeCustom];
    self.feedBack.frame = CGRectMake(10, splitLine4.frame.origin.y + 1, kScreen_Width  - 20, buttonHeight);
    [self.feedBack setTitle:@"意见反馈" forState:UIControlStateNormal];
    self.feedBack.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.feedBack addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.feedBack.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.scrollView addSubview:self.feedBack];
    
    
    //split line
    UIImageView *splitLine5 = [[UIImageView alloc] initWithImage:line];
    splitLine5.frame = CGRectMake(10, self.feedBack.frame.origin.y + buttonHeight + 1, 300, 1);
    [self.scrollView addSubview:splitLine5];
    
    
    // Copyright
    self.copyright = [UIButton buttonWithType:UIButtonTypeCustom];
    self.copyright.frame = CGRectMake(10, splitLine5.frame.origin.y + 1, kScreen_Width  - 20, buttonHeight);
    [self.copyright setTitle:@"版权信息" forState:UIControlStateNormal];
    self.copyright.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.copyright addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.copyright.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.scrollView addSubview:self.copyright];
    
    
    //split line
    UIImageView *splitLine6 = [[UIImageView alloc] initWithImage:line];
    splitLine6.frame = CGRectMake(10, self.copyright.frame.origin.y + buttonHeight + 1, 300, 1);
    [self.scrollView addSubview:splitLine6];
    
    
    // Evaluation
    self.evaluation = [UIButton buttonWithType:UIButtonTypeCustom];
    self.evaluation.frame = CGRectMake(10, splitLine6.frame.origin.y + 1, kScreen_Width  - 20, buttonHeight);
    [self.evaluation setTitle:@"评价App" forState:UIControlStateNormal];
    self.evaluation.titleLabel.font = [UIFont systemFontOfSize:14];

    [self.evaluation addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.evaluation.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.scrollView addSubview:self.evaluation];
    
    
    //split line
    UIImageView *splitLine7 = [[UIImageView alloc] initWithImage:line];
    splitLine7.frame = CGRectMake(10, self.evaluation.frame.origin.y + buttonHeight + 1, 300, 1);
    [self.scrollView addSubview:splitLine7];
    
    
    // Update
    self.update = [UIButton buttonWithType:UIButtonTypeCustom];
    self.update.frame = CGRectMake(10, splitLine7.frame.origin.y + 1, kScreen_Width  - 20, buttonHeight);
    [self.update setTitle:@"版本更新" forState:UIControlStateNormal];
    self.update.titleLabel.font = [UIFont systemFontOfSize:14];

    [self.update addTarget:self action:@selector(handleButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.update.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.scrollView addSubview:self.update];
    
    
    // LogOut
    self.logout = [UIButton buttonWithType:UIButtonTypeCustom];
    self.logout.frame = CGRectMake(110, self.update.frame.origin.y + 30 + 20, 100, 34);
    [self.logout setBackgroundImage:[UIImage imageNamed:@"me_btn_bg.png"] forState:UIControlStateNormal];
    UIImage* image = [Common createImageWithColor:RGB(167, 167, 171) andSize:CGSizeMake(100, 34)];
    [self.logout setBackgroundImage:image forState:UIControlStateDisabled];
    
    if([[UserObj sharedInstance] isLegalLogin])
    {
        self.logout.enabled = YES;
    }
    else{
        self.logout.enabled = NO;
    }
    
    [self.logout setTitle:@"退出登录" forState:UIControlStateNormal];
    self.logout.layer.cornerRadius = 5;
    self.logout.clipsToBounds = YES;
    self.logout.titleLabel.font = [UIFont systemFontOfSize:14];

    [self.logout addTarget:self action:@selector(logOut) forControlEvents:UIControlEventTouchUpInside];
    self.logout.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.scrollView addSubview:self.logout];
    self.scrollView.contentHeight = self.logout.bottom+10;
    [self performSelector:@selector(getImageCacheSizeAndZero:) withObject:nil afterDelay:0.0];

}

- (void) handleSwithEvent: (CCSwitch *) sender
{
    
    if(sender == self.sw)
    {
        NSUserDefaults *userDefault= [NSUserDefaults standardUserDefaults];
        [userDefault setBool:self.sw.on forKey:IsAllowedDownloadIn3G];
        [userDefault synchronize];
    }
    else
    {
        NSUserDefaults *userDefault= [NSUserDefaults standardUserDefaults];
        [userDefault setBool:self.pushSw.on forKey:IsAllowedPush];
        [userDefault synchronize];
    }
}

- (void) handleButtonEvent: (UIButton *) sender
{
    [kApp hideWaitView];
    if(sender == self.personSetting)
    {
    if([[UserObj sharedInstance] isLegalLogin])
    {
        PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithNibName:@"PersonalInfoViewController" bundle:nil];
        [self.navigationController pushViewController:personalInfoVC animated:YES];
    }
    else{
        [PopTips tips:kApp.rootNav.view Msg:NotifyLoginFirst];
        kApp.meHomeVC = [[MeHomeViewController alloc] initWithNibName:@"MeHomeViewController" bundle:nil];
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    }
    
    if (sender == self.networkSetting) {
        
    }
    if (sender == self.pushSetting) {
        
    }
    if (sender == self.clearSpace) {
        [self clearTheImageCache];
    }
    if (sender == self.privateTerm) { //隐私
        [self handleInfoWithTag:1 andWithTitle:@"隐私政策"];
    }
    if (sender == self.feedBack) { //意见反馈
        [self handleInfoWithTag:2 andWithTitle:@"意见反馈"];
    }
    if (sender == self.copyright) { //版权信息
        [self handleInfoWithTag:3 andWithTitle:@"版权信息"];
    }
    if (sender == self.evaluation) {
        [Common goToAppStore];
    }
    if (sender == self.update) {
        [self checkNewVersion];
    }
}

#pragma mark - appStore
-(void)goToAppStore
{
    [kApp displayWaitViewWithAllMaskView:NO];
    
    //初始化控制器
    SKStoreProductViewController *storeProductViewContorller = [[SKStoreProductViewController alloc] init];
    //设置代理请求为当前控制器本身
    storeProductViewContorller.delegate = self;
    //加载一个新的视图展示
    [storeProductViewContorller loadProductWithParameters:
     //appId唯一的
     @{SKStoreProductParameterITunesItemIdentifier : AppleAppID} completionBlock:^(BOOL result, NSError *error) {
         //block回调
         if(error){
            [kApp hideWaitView];
         }else{
             //模态弹出appstore
             [self presentViewController:storeProductViewContorller animated:YES completion:^{
                 [kApp hideWaitView];
             }
              ];
         }
     }];

}

//取消按钮监听
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController{
   
    [kApp hideWaitView];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


#pragma mark - 清理缓存
-(void)clearTheImageCache{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:NotifyNormal message:NotifyCacheClear delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 100;
    [alert show];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
   if(alertView.tag == 100)
   {
    if (buttonIndex) {
        //[XAppDelegate displayWaitViewWithAllMaskView:YES];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [[SDImageCache sharedImageCache] clearDisk];
            dispatch_async(dispatch_get_main_queue(), ^{
                //[XAppDelegate hideWaitView];
                [self getImageCacheSizeAndZero:YES];
            });
        });
    }
   }
    if(alertView.tag == 102)
    {
        if(buttonIndex)
        {
            [self goToAppStore];
        }
    }
}

-(void)getImageCacheSizeAndZero:(BOOL)flag{
   
    if (flag) {
        self.clearLabel.text=@"0.0M";
    }else{
        self.clearLabel.text=[NSString stringWithFormat:@"%.1fM",[LocalFileManage bytesTransformToM:[[SDImageCache sharedImageCache] getSize]]];
    }
}


#pragma mark - 版本更新
-(void)checkNewVersion{
    NSString * url = [NSString stringWithFormat:@"%@updateVersion&pf=2",API_BASE];
    
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self checkVersionSuccess:responseObj];
        }
        else
        {
            [self checkVersionError];
        }
    }];
}

-(void)checkVersionSuccess:(id)responseObj
{
    
    NSDictionary* dic = (NSDictionary*)responseObj;
    float appVersion = [[dic objectForKey:@"version_number"] floatValue];
    if(appVersion <= [APPVersion floatValue])
    {
        [PopTips tipsAtTop:self.view Msg:NotifyVersionHaveNO];
    }
    else{
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:NotifyNormal message:NotifyVersionHave delegate:self cancelButtonTitle:@"再等等" otherButtonTitles:@"立即开启", nil];
        alert.tag = 102;
        [alert show];
        
    }
}

-(void)checkVersionError
{
    [PopTips tips:self.view Msg:NotifyNoNet];
}


-(void)handleInfoWithTag:(int)tag andWithTitle:(NSString*)title
{
    SystemSettingInfoVC* infoVC = [[SystemSettingInfoVC alloc]initWithNibName:@"SystemSettingInfoVC" bundle:nil];
    infoVC.title = title;
    infoVC.tag = tag;
    [self.navigationController pushViewController:infoVC animated:YES];
}

- (void) logOut
{
        [[UserObj sharedInstance] logout];
        [self.navigationController popViewControllerAnimated:YES];
}

- (void) popOut
{
    [kApp hideWaitView];
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - faker


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

@end
